package com.ccys.doctor.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.ccys.common.constants.ContextConstants;
import com.ccys.common.third.aws.s3.S3Util;
import com.ccys.common.third.pubnub.Message;
import com.ccys.common.third.pubnub.PubNubHelper;
import com.ccys.common.third.twilio.TwilioVoiceCallUtil;
import com.ccys.common.vo.ResponseResultApp;
import com.ccys.db.cache.UserUtil;
import com.ccys.db.dto.doctor.consultStage.*;
import com.ccys.db.dto.member.GetTwilioTokenDto;
import com.ccys.db.entity.TblBookingPatientAddress;
import com.ccys.db.entity.TblBookingTextBasedDelMsg;
import com.ccys.db.entity.TblMember;
import com.ccys.db.mapper.*;
import com.ccys.db.page.AppPageDto;
import com.ccys.db.vo.doctor.consultStage.*;
import com.ccys.doctor.service.BookingPatientAddressService;
import com.ccys.doctor.service.ConsultStageService;
import com.ccys.doctor.service.MemberService;
import com.github.pagehelper.PageInfo;
import com.google.api.client.util.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author：XLY 从Consult Stage 28行开始
 * @Date：2024/2/21 0021
 */
@RestController
@RequestMapping("/consultStage")
@Api(tags = "Consult Stage")
@Slf4j
public class ConsultStageController {


    @Resource
    private TblRecommendReminderMapper recommendReminderMapper;


    @Resource
    private TblMedicalServiceMapper medicalServiceMapper;


    @Resource
    private TblProductMapper productMapper;


    @Resource
    private TblLabResultMapper labResultMapper;


    @Resource
    private TblMemberLongTermMapper longTermMapper;


    @Resource
    private TblBookingMemberInfoMapper memberInfoMapper;


    @Resource
    private TblBookingPatientAddressMapper patientAddressMapper;


    @Resource
    private BookingPatientAddressService patientAddressService;


    @Resource
    private TblPhqMapper phqMapper;


    @Resource
    private TblTemplateMapper templateMapper;


    @Resource
    private TblBookingTextBasedDelMsgMapper delMsgMapper;


    @Resource
    private ConsultStageService consultStageService;


    @Resource
    private TblBookingSummaryMapper summaryMapper;


    @Resource
    private PubNubHelper pubNubHelper;


    @Resource
    private MemberService memberService;


    @ApiOperation("Consult Stage/ 28")
    @GetMapping("GetGraphBloodPressure")
    public ResponseResultApp<GetGraphBloodPressureVo> getGraphBloodPressure(GetGraphBloodPressureDto dto) {
        if (Objects.nonNull(dto.getLast_month_type())) {

            String child_id = dto.getChild_id();
            if (StringUtils.isNotEmpty(child_id)) {
                dto.setMember_id(child_id);
            }
            List<GetGraphBloodPressureVo.BloodPressureVo> bloodPressureList = recommendReminderMapper.getGraphBloodPressure(dto.getMember_id(), dto.getLast_month_type());

            //求平均值
            int avgSystolic = (int) bloodPressureList.stream().filter(x -> Objects.nonNull(x.getSystolic())).mapToInt(GetGraphBloodPressureVo.BloodPressureVo::getSystolic).average().orElse(0);
            int avgDiastolic = (int) bloodPressureList.stream().filter(x -> Objects.nonNull(x.getDiastolic())).mapToInt(GetGraphBloodPressureVo.BloodPressureVo::getDiastolic).average().orElse(0);
            int avgHeartRate = (int) bloodPressureList.stream().filter(x -> Objects.nonNull(x.getHeartRate())).mapToInt(GetGraphBloodPressureVo.BloodPressureVo::getHeartRate).average().orElse(0);
            GetGraphBloodPressureVo.AvgBloodPressureVo avgBloodPressureVo = new GetGraphBloodPressureVo.AvgBloodPressureVo();
            avgBloodPressureVo.setAvgDiastolic(avgDiastolic);
            avgBloodPressureVo.setAvgSystolic(avgSystolic);
            avgBloodPressureVo.setAvgHeartRate(avgHeartRate);

            //获得月份并去重
            Set<Integer> mouthSet = bloodPressureList.stream().map(x -> {
                Date date = x.getUtcDateToTakeRecommend();
                return DateUtil.month(date) + 1;
            }).collect(Collectors.toSet());

            List<GetGraphBloodPressureVo.MonthVo> monthList = mouthSet.stream().map(x -> {
                GetGraphBloodPressureVo.MonthVo monthVo = new GetGraphBloodPressureVo.MonthVo();
                monthVo.setMonth(x);
                return monthVo;
            }).collect(Collectors.toList());

            GetGraphBloodPressureVo vo = new GetGraphBloodPressureVo();
            vo.setBloodPressures(bloodPressureList);
            vo.setAvgBloodPressure(avgBloodPressureVo);
            vo.setLastMonth(monthList);
            return ResponseResultApp.success(vo);
        }

        return ResponseResultApp.success();
    }


    @ApiOperation("Consult Stage/ 29")
    @GetMapping("GetGraphBloodSugar")
    public ResponseResultApp<List<GetGraphBloodSugarVo>> getGraphBloodSugar(GetGraphBloodSugarDto dto) {
        String child_id = dto.getChild_id();
        if (StringUtils.isNotEmpty(child_id)) {
            dto.setMember_id(child_id);
        }
        List<GetGraphBloodSugarVo> voList = recommendReminderMapper.getGraphBloodSugar(dto.getMember_id(), dto.getFilter_time_type());
        return ResponseResultApp.success(voList);
    }


    @ApiOperation("Consult Stage/ 30")
    @GetMapping("GetHeartRateHistory")
    public ResponseResultApp<GetHeartRateHistoryVo> getHeartRateHistory(String member_id) {
        List<GetHeartRateHistoryVo.HeartRateVo> heartRateHistory = labResultMapper.getHeartRateHistory(member_id);
        GetHeartRateHistoryVo vo = new GetHeartRateHistoryVo();
        vo.setHeartRates(heartRateHistory);
        return ResponseResultApp.success();
    }


    @ApiOperation("Consult Stage/ 31")
    @GetMapping("GetIndoSPMedication")
    public ResponseResultApp<List<GetIndoSPMedicationVo>> getIndoSPMedication() {
        List<GetIndoSPMedicationVo.IndoSPMedicationVo> medicationList = productMapper.getIndoSPMedication();
        //product_name = drug_name + composition
        //ingredient_only = composition
        //name_only = drug_name
        List<GetIndoSPMedicationVo> res = medicationList.stream().map(x -> {
            List<GetIndoSPMedicationVo.CompositionVo> compositionList = x.getCompositionList();

            String temp = compositionList.stream().map(GetIndoSPMedicationVo.CompositionVo::getComposition).collect(Collectors.joining());
            String ingredientOnly = "";
            if (StringUtils.isNotEmpty(temp)) {
                ingredientOnly = " (" + temp + ")";
            }
            x.setNameOnly(x.getProductName());
            x.setProductName(x.getNameOnly() + ingredientOnly);
            x.setIngredientOnly(ingredientOnly);

            GetIndoSPMedicationVo vo = new GetIndoSPMedicationVo();
            vo.setSource(x);
            return vo;
        }).collect(Collectors.toList());
        return ResponseResultApp.success(res);
    }


    @ApiOperation("Consult Stage/ 32")
    @GetMapping("GetLisLaboratoryResult")
    public ResponseResultApp<GetLisLaboratoryResultVo> getLisLaboratoryResult(String memberId) {
        List<GetLisLaboratoryResultVo.LaboratoryVo> res = labResultMapper.getLisLaboratoryResult(memberId);
        res.forEach(x -> {
            //得到PDF的链接
            String autoPDF = x.getAutoPDF();
            String path = "";
            if (StringUtils.isNotEmpty(autoPDF)) {
                //这个autoPDF是文件路径
                path = x.getAutoPDF();
            } else {
                path = "LaboratoryResult/" + x.getLabResultPDF();

            }
            String presignedUrl = S3Util.createPresignedGetUrl(path);
            x.setLabResultPDF(presignedUrl);
        });
        GetLisLaboratoryResultVo vo = new GetLisLaboratoryResultVo();
        vo.setLaboratories(res);
        return ResponseResultApp.success(vo);
    }


    @ApiOperation("Consult Stage/ 34")
    @GetMapping("GetLongterm")
    public ResponseResultApp<List<GetLongTermVo>> getLongTerm(String member_id) {
        List<GetLongTermVo> res = longTermMapper.getLongTerm(member_id);
        return ResponseResultApp.success(res);
    }

    @ApiOperation("Consult Stage/ 35")
    @GetMapping("GetMasterDataOfSpecificConsultation")
    public ResponseResultApp<GetMasterDataVo> getMasterDataOfSpecificConsultation(GetMasterDataOfSpecificConsultationDto dto) {
        GetMasterDataVo res = consultStageService.getMasterDataOfSpecificConsultation(dto);
        return ResponseResultApp.success(res);
    }


    @ApiOperation("Consult Stage/ 36")
    @GetMapping("GetMasterData")
    public ResponseResultApp<GetMasterDataVo> getMasterData() {
        GetMasterDataVo vo = consultStageService.getMasterData();
        return ResponseResultApp.success(vo);
    }

    @ApiOperation("Consult Stage/ 37")
    @GetMapping("GetMedicalService")
    public ResponseResultApp<List<GetMedicalServiceVo>> getMedicalService(String bookingId) {
        //根据doctorid以及bookingId查到medicalservice是walkin 还是homebase
        DoctorMedicalServiceTypeVo doctorMedicalServiceType = medicalServiceMapper.getDoctorMedicalServiceTypeByBookingId(bookingId);
        if (Objects.nonNull(doctorMedicalServiceType)) {
            Integer allowWalkInServices = doctorMedicalServiceType.getAllowWalkInServices();
            Integer allowHomeBaseServices = doctorMedicalServiceType.getAllowHomeBaseServices();
            if (Objects.isNull(allowHomeBaseServices)) {
                allowHomeBaseServices = 0;
            }
            if (Objects.isNull(allowWalkInServices)) {
                allowWalkInServices = 0;
            }

            //根据bookingId查到这个病人在问诊使用的benefit，benefit里面有medical_service_exclusion_list_id
            String medicalServiceExclusionList = medicalServiceMapper.getMedicalServiceExclusionList(bookingId);
            //查询tbl_medical_service以及tbl_package（属于service的package）
            List<GetMedicalServiceVo> medicalService = medicalServiceMapper.getMedicalService(medicalServiceExclusionList, allowWalkInServices, allowHomeBaseServices);
            return ResponseResultApp.success(medicalService);
        }


        return ResponseResultApp.success();
    }

    @ApiOperation("Consult Stage/ 38")
    @GetMapping("GetMedicalServiceByPackage")
    public ResponseResultApp<List<GetMedicalServiceByPackageVo>> getMedicalServiceByPackage(String packageId) {
        List<GetMedicalServiceByPackageVo> res = medicalServiceMapper.getMedicalServiceByPackage(packageId);
        return ResponseResultApp.success(res);
    }


    @ApiOperation("Consult Stage/ 39")
    @GetMapping("GetMedicationByPackage")
    public ResponseResultApp<List<GetMedicationByPackageVo>> getMedicationByPackage(String packageId) {
        List<GetMedicationByPackageVo> res = productMapper.getMedicationByPackage(packageId);
        return ResponseResultApp.success(res);
    }


    @ApiOperation("Consult Stage/ 40")
    @GetMapping("GetMedicationFavouritePrescription")
    public ResponseResultApp<List<GetMedicationFavouriteWithCountryVo>> getMedicationFavouritePrescription() {
        String curLoginUserId = UserUtil.getCurLoginUserId();
        List<GetMedicationFavouriteWithCountryVo> res = productMapper.getMedicationFavouritePrescription(curLoginUserId);
        prepareDrugName(res);
        return ResponseResultApp.success(res);
    }


    private void prepareDrugName(List<? extends GetMedicationFavouriteWithCountryVo> medicationList) {
        // IngredientOnly 是把药品所有的Ingredient name + dosage 用逗号连接起来
        // nameOnly 是药品的名字
        // name 是 nameOnly + IngredientOnly
        medicationList.forEach(x -> {
            List<GetMedicationFavouriteWithCountryVo.IngredientVo> ingredientList = x.getIngredientList();
            String temp = ingredientList.stream().map(y -> y.getName() + " " + y.getDosage()).collect(Collectors.joining());
            String ingredientOnly = "";
            if (StringUtils.isNotEmpty(temp)) {
                ingredientOnly = " (" + temp + ")";
            }
            x.setName(x.getNameOnly() + ingredientOnly);
            x.setIngredientOnly(ingredientOnly);
        });
    }


    @ApiOperation("Consult Stage/ 41")
    @GetMapping("GetMedicationFavouriteWithCountry")
    public ResponseResultApp<List<GetMedicationFavouriteWithCountryVo>> getMedicationFavouriteWithCountry() {
        String curLoginUserId = UserUtil.getCurLoginUserId();
        List<GetMedicationFavouriteWithCountryVo> medicationList = productMapper.getMedicationFavouriteWithCountry(curLoginUserId);
        prepareDrugName(medicationList);
        return ResponseResultApp.success(medicationList);
    }


    @ApiOperation("Consult Stage/ 42")
    @GetMapping("GetMedicationForCdmp")
    public ResponseResultApp<List<GetMedicationForCdmpVo>> getMedicationForCdmp() {
        List<GetMedicationForCdmpVo> res = productMapper.getMedicationForCdmp();
        return ResponseResultApp.success(res);
    }

    @ApiOperation("Consult Stage/ 43")
    @GetMapping("GetMedicationGoApotik")
    public ResponseResultApp<List<GetMedicationGoApotikVo>> getMedicationGoApotik(String searchText) {
        List<GetMedicationGoApotikVo> res = productMapper.getMedicationGoApotik(searchText);
        return ResponseResultApp.success(res);
    }


    @ApiOperation("Consult Stage/ 44")
    @GetMapping("GetMedicationGoApotikDetail")
    public ResponseResultApp<GetMedicationGoApotikDetailVo> getMedicationGoApotikDetail(String productId) {
        GetMedicationGoApotikDetailVo res = productMapper.getMedicationGoApotikDetail(productId);
        return ResponseResultApp.success(res);
    }


    @ApiOperation("Consult Stage/ 45")
    @GetMapping("GetMedicationGroup")
    public ResponseResultApp<List<GetMedicationGroupVo>> getMedicationGroup() {
        List<GetMedicationGroupVo> res = productMapper.getMedicationGroup();
        return ResponseResultApp.success(res);
    }


    @ApiOperation("Consult Stage/ 46")
    @GetMapping("GetMedicationWithCountry")
    public ResponseResultApp<List<GetMedicationWithCountryVo>> getMedicationWithCountry(String booking_id) {
        //根据booking找到member的countryOfResidence
        //根据bookingId找到benefit，得到benefit的drug_inclusion_list_id、visit_balance、max_amount
        // is_in_exclusion_list 的逻辑:
        // Case When (@visit_balance !=0 and @max_amount != 0  and ((@drug_exclusion_list_id is not null and drug_exclusion_list.ProductList_Id is not null)
        // or (@drug_inclusion_list_id is not null and drug_inclusion_list.ProductList_Id is null)))
        // cdmp 的 drug_exclusion_list_id 是这个 drug_inclusion_list_id ，因为一个booking对应一个benefit
        // 所以逻辑简化为(@visit_balance !=0 and @max_amount != 0 and find_in_set(productId,drug_exclusion_list_id)) = is_in_exclusion_list
        // booking中spelialistId 为2或者3的时候，对应tblPlanBenefitService中type为2
        // booking中spelialistId 为5，对应tblPlanBenefitService中type为8
        // booking中spelialistId 为1，对应tblPlanBenefitService中type为3
        // booking中consultType 为1，对应tblPlanBenefitService中type为0
        // TODO: 2024/2/22 0022 这个maxAmount和visitBalance逻辑抽象先不管
        List<GetMedicationWithCountryVo> medicationList = productMapper.getMedicationWithCountry(booking_id);
        prepareDrugName(medicationList);

        return ResponseResultApp.success(medicationList);
    }


    @ApiOperation("Consult Stage/ 47")
    @GetMapping("GetMedicationWithIsExclusionList")
    public ResponseResultApp<List<GetMedicationWithCountryVo>> getMedicationWithIsExclusionList(String booking_id) {
        List<GetMedicationWithCountryVo> medicationList = productMapper.getMedicationWithIsExclusionList(booking_id);
        prepareDrugName(medicationList);

        return ResponseResultApp.success();
    }


    @ApiOperation("Consult Stage/ 48")
    @GetMapping("GetMemberDetail")
    public ResponseResultApp getMemberDetail(String member_id, String child_id) {
        member_id = StringUtils.isNotEmpty(child_id) ? child_id : member_id;
        String curLoginUserId = UserUtil.getCurLoginUserId();
        GetMemberDetailVo memberDetail = memberInfoMapper.getMemberDetail(member_id, curLoginUserId);
        //todo 有关photo的东西需要组装路径
        return ResponseResultApp.success(memberDetail);
    }

    @ApiOperation("Consult Stage/ 49")
    @GetMapping("GetNRICLogToVerified")
    public ResponseResultApp<List<GetNRICLogToVerifiedVo>> getNRICLogToVerified(String member_id) {
        List<GetNRICLogToVerifiedVo> res = memberInfoMapper.getNRICLogToVerified(member_id);
        res.forEach(x -> {
            //处理createdOnDisplay
            String display = consultStageService.prepareCreatedOnDisplay(x.getCreatedOn());
            x.setCreatedOnDisplay(display);
        });
        return ResponseResultApp.success(res);
    }


    @ApiOperation("Consult Stage/ 50")
    @PostMapping("GetOrUpdateConsultingFromAddress")
    @Transactional
    public ResponseResultApp<GetOrUpdateConsultingFromAddressVo> getOrUpdateConsultingFromAddress(@RequestBody GetOrUpdateConsultingFromAddressDto dto) {

        String action = dto.getAction();
        if ("UPDATE".equals(action)) {
            TblBookingPatientAddress model = new TblBookingPatientAddress();
            model.setId(dto.getId());
            model.setPostalCode(dto.getPostal_code());
            model.setAddress(dto.getAddress());
            model.setLatitude(dto.getLatitude());
            model.setLongitude(dto.getLongitude());
            model.setCountry(dto.getCountry());
            model.setState(dto.getState());
            model.setUnitNumber(dto.getFloor_number());
            patientAddressService.insertOrUpdate(model);
        } else {
            GetOrUpdateConsultingFromAddressVo res = patientAddressMapper.getOrUpdateConsultingFromAddress(dto.getBooking_id());
            return ResponseResultApp.success(res);
        }
        return ResponseResultApp.success();
    }


    @ApiOperation("Consult Stage/ 51")
    @GetMapping("GetPastConsultationsDetail")
    public ResponseResultApp<GetPastConsultationsDetailVo> getPastConsultationsDetail(String booking_id) {
        //booking_id = 59B78D6A-C63C-469A-831E-B581F0C01041
        //GetBookingDetail
        // TODO: 2024/3/1 0001 1/diagnosis_html 2/memoFile,symptom photos路径
        // 这个表tbl_booking_medical_service里面有in_exclusion_list
        // memo showmemo
        GetPastConsultationsDetailVo vo = summaryMapper.getPastConsultationsDetailVo(booking_id);
        GetPastConsultationsDetailVo.MemoInfoVo memoInfoVo = new GetPastConsultationsDetailVo.MemoInfoVo();
        memoInfoVo.setMemo(vo.getMemo());
        memoInfoVo.setShowMemo(vo.getShowMemo());
        memoInfoVo.setMemoFile(vo.getMemoFile());
        // prescription nameOnly
        List<GetPastConsultationsDetailVo.PrescriptionVo> prescription = vo.getPrescription();
        if (CollectionUtils.isNotEmpty(prescription)) {
            prescription.forEach(x -> {
                List<GetPastConsultationsDetailVo.IngredientVo> ingredientList = x.getIngredientList();
                String temp = ingredientList.stream().map(y -> {
                    String dosage = StringUtils.isNotEmpty(y.getDosage()) ? " " + y.getDosage() : "";
                    return y.getName() + dosage;
                }).collect(Collectors.joining());
                String ingredientOnly = "";
                if (StringUtils.isNotEmpty(temp)) {
                    ingredientOnly = " (" + temp + ")";
                }
                x.setName(x.getNameOnly() + ingredientOnly);
                x.setIngredientOnly(ingredientOnly);
            });
        }
        return ResponseResultApp.success();
    }


    @ApiOperation("Consult Stage/ 52")
    @GetMapping("GetPatienInfotListing")
    public ResponseResultApp<GetPatienInfotListingVo> getPatientInfoListing(GetPatienInfotListingDto dto) {
        GetPatienInfotListingVo vo = new GetPatienInfotListingVo();
        //如果是offline
        //直接根据查询条件查询member表，要分页
        Integer forOffline = dto.getForOffline();
        AppPageDto.startPage();
        List<GetPatienInfotListingVo.PatientVo> patients = Lists.newArrayList();
        if (Objects.nonNull(forOffline) && forOffline.equals(1)) {
            patients = memberInfoMapper.getPatientInfoListingForOffline(dto);
        } else {
            //如果不是offline
            //查询tbl_doctor的is_full_access
            //根据查询条件以及is_full_access查询tbl_booking关联tbl_member，要分页
            String doctorId = UserUtil.getCurLoginUserId();
            patients = memberInfoMapper.getPatientInfoListing(doctorId, dto);
        }

        PageInfo<GetPatienInfotListingVo.PatientVo> pageInfo = new PageInfo<>(patients);
        vo.setPatients(patients);
        vo.setTotalPage(pageInfo.getPages());
        vo.setCurrentPage(pageInfo.getPageNum());
        return ResponseResultApp.success();
    }


    @ApiOperation("Consult Stage/ 53")
    @GetMapping("GetPHQ4Question")
    public ResponseResultApp<List<GetPHQ4QuestionVo>> getPHQ4Question(Integer service_type) {
        List<GetPHQ4QuestionVo> res = phqMapper.getPHQ4Question(service_type);
        //CheckIsRequestPHQ4
        //CheckIsOnBoarding
        return ResponseResultApp.success(res);
    }


    @ApiOperation("Consult Stage/ 54")
    @GetMapping("GetPHQ4Response")
    public ResponseResultApp<List<GetPHQ4ResponseVo>> getPHQ4Response(String member_id, String child_id) {
        member_id = StringUtils.isNotEmpty(child_id) ? child_id : member_id;
        List<GetPHQ4ResponseVo> res = phqMapper.getPHQ4Response(member_id);
        return ResponseResultApp.success(res);
    }

    @ApiOperation("Consult Stage/ 55")
    @GetMapping("GetRecommendedCategories")
    public ResponseResultApp<List<String>> getRecommendedCategories(String booking_id) {
        List<String> res = phqMapper.getRecommendedCategories(booking_id);
        return ResponseResultApp.success(res);
    }


    @ApiOperation("Consult Stage/ 56")
    @GetMapping("GetTBTCConsultingPatient")
    public ResponseResultApp getTBTCConsultingPatient(String timeslot) {
        return consultStageService.getTBTCConsultingOrIncomingPatient(timeslot, "consulting");
    }


    @ApiOperation("Consult Stage/ 57")
    @GetMapping("GetTemplateActive")
    public ResponseResultApp<List<GetTemplateActiveVo>> getTemplateActive() {
        List<GetTemplateActiveVo> res = templateMapper.getTemplateActive();
        return ResponseResultApp.success(res);
    }


    @ApiOperation("Consult Stage/ 58")
    @GetMapping("GetTextBasedFiles")
    public ResponseResultApp<List<GetTextBasedFilesVo>> getTextBasedFiles(String booking_id) {
        List<Message> historyFile = pubNubHelper.getHistoryFile(booking_id);
        if (CollectionUtils.isNotEmpty(historyFile)) {
            List<GetTextBasedFilesVo> collect = historyFile.stream().map(x -> {
                GetTextBasedFilesVo vo = new GetTextBasedFilesVo();
                vo.setUuid(x.getUuid());
                vo.setName(x.getMessage().getFile().getName());
                vo.setTimetoken(x.getTimetoken());
                vo.setUrl(x.getMessage().getFile().getUrl());
                return vo;
            }).collect(Collectors.toList());
            return ResponseResultApp.success(collect);
        }
        return ResponseResultApp.success(new ArrayList<>());
    }


    @ApiOperation("Consult Stage/ 59")
    @GetMapping("GetTextTemplate")
    public ResponseResultApp<GetTextTemplateVo> getTextTemplate(String keyword, Integer is_default) {
        String doctorId = UserUtil.getCurLoginUserId();
        AppPageDto.startPage();
        List<GetTextTemplateVo.TextTemplateVo> textTemplate = templateMapper.getTextTemplate(doctorId, keyword, is_default);
        PageInfo<GetTextTemplateVo.TextTemplateVo> info = new PageInfo<>(textTemplate);
        GetTextTemplateVo vo = new GetTextTemplateVo();
        vo.setTotal_page(info.getPages());
        vo.setTextTemplates(textTemplate);
        return ResponseResultApp.success(vo);
    }


    @ApiOperation("Consult Stage/ 60")
    @GetMapping("GetTextTemplateByDoctorId")
    public ResponseResultApp getTextTemplateByDoctorId() {
        String doctorId = UserUtil.getCurLoginUserId();
        List<GetTextTemplateByDoctorIdVo.TextTemplateVo> res = templateMapper.getTextTemplateByDoctorId(doctorId);
        GetTextTemplateByDoctorIdVo vo = new GetTextTemplateByDoctorIdVo();
        vo.setTextTemplates(res);
        return ResponseResultApp.success(vo);
    }

    @ApiOperation("获取视频的AccessToken/61")
    @GetMapping(value = "/GetTwilioToken")
    public ResponseResultApp GetTwilioToken(GetTwilioTokenDto dto){
        String twilioVideoToken = TwilioVoiceCallUtil.getTwilioVideoToken(UserUtil.getCurLoginUserId(), dto.getId());
        return ResponseResultApp.success(twilioVideoToken);
    }


    @ApiOperation("Consult Stage/ 62")
    @GetMapping(" RejectNricChange")
    public ResponseResultApp rejectNricChange(String member_id) {
        RejectNricChangeVo res = memberInfoMapper.rejectNricChange(member_id);
        TblMember member = new TblMember();
        member.setDoctorVerified(0);
        member.setVerifiedDoctorId("");
        member.setPendingNric("");
        member.setIsNeedVerifyWhenRegister(0);
        member.setId(member_id);
        memberService.insertOrUpdate(member);
        return ResponseResultApp.success(res);
    }


    @ApiOperation("Consult Stage/ 63")
    @PostMapping("RemoveTextBaseMessage")
    public ResponseResultApp removeTextBaseMessage(@RequestBody RemoveTextBaseMessageDto dto) {
        TblBookingTextBasedDelMsg delMsg = new TblBookingTextBasedDelMsg();
        delMsg.setId(IdUtil.getSnowflakeNextIdStr());
        delMsg.setMessage(dto.getMessage());
        delMsg.setBookingId(dto.getBooking_id());
        delMsg.setTimetoken(dto.getTimetoken());
        delMsg.setAccountType("doctor");
        delMsgMapper.insert(delMsg);
        return ResponseResultApp.success();
    }


    /**
     * @param param   这是一个json串 {"booking_id":"3bde2ce0-abc1-472a-a5fc-fe21f895c73e","files":[{"id":"f82be819-b807-4c07-af66-806a48be7645","file":null,"name":"jack sparrow.jpg","width":2047,"height":1199}]}
     * @return
     */
    @ApiOperation("Consult Stage/ 89")
    @PostMapping("UploadTextBasedFiles")
    public ResponseResultApp uploadTextBasedFiles(String param, HttpServletRequest request){
        try {
            //下面这句必须加，不然报错
            MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            //获取上传上来的文件
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            return consultStageService.uploadTextBasedFiles(param, fileMap);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return ResponseResultApp.success();
    }



    @ApiOperation("Consult Stage/ 90")
    @PostMapping("UpsertPrescription")
    public ResponseResultApp upsertPrescription(@RequestBody UpsertPrescriptionDto dto){

        return ResponseResultApp.success();
    }
}
